<?php
namespace app\admin\controller;

use think\App;
use think\Db;
use app\admin\model\HouseProperty as PropertyModel;
use app\admin\model\HouseBilling as BillingModel;
use app\admin\model\BillSum as SumModel;
use app\admin\model\AdminUser as UserModel;

class Index extends Common
{
    protected $checkLoginExclude = ['login', 'logout'];

    public function index()
    {
        $controller = $this->request->controller();
        $this->assign('layout_menu', $this->auth->menu($controller));
        return $this->fetch();
    }
    
    public function login()
    {
        if ($this->request->isPost()) {
            $data = [
                'username' => $this->request->post('username/s', '', 'trim'),
                'password' => $this->request->post('password/s', ''),
            ];
            if (!$this->auth->login($data['username'], $data['password'])) {
                $this->error('登陆失败：' . $this->auth->getError() . '。');
            }
            $this->success('登陆成功。');
        }
        $this->assign('token', $this->getToken());
        return $this->fetch();
    }

    public function logout()
    {
        $this->auth->logout();
        $this->redirect('Index/login');
    }

    public function welcome()
    {
        $loginUser = $this->auth->getLoginUser();
        $property_count = PropertyModel::where('admin_user_id', $loginUser['id'])->count();
        $user = UserModel::get($loginUser['id']);
        $number_count =  $user->houseNumber->count();
        $empty_count =  $user->houseNumber->where('rent_mark', 'N')->count();
        $occupancy = $number_count == 0 ? '0%' : round((($number_count - $empty_count)/$number_count)*100).'%';
        $this->assign('house_info', [
            'property_count' => $property_count,
            'number_count' => $number_count,
            'empty_count' => $empty_count,
            'occupancy' => $occupancy,
            'overdue_todo' => $user->houseBilling->where('accounting_date', null)
                ->where('meter_reading_time', '=', '')
                ->where('start_time', '<', date('Y-m-d H:i:s', time()))
                ->count(),
            'overdue_uncollected' => $user->houseBilling->where('accounting_date', null)
                ->where('meter_reading_time', '!=', '')
                ->where('start_time', '<', date('Y-m-d H:i:s', time()))
                ->count(),
        ]);
        $property = PropertyModel::where('admin_user_id', $loginUser['id'])->select()->toArray();
        $result = array_map(function ($item) {
            return $item['id'];
        }, $property);
        $star = date("Y-m-01", time());
        $end = date("Y-m-t", time());
        //应收
        $receivable = BillingModel::where('house_property_id', 'in', $result)
        ->whereTime('start_time', [$star, $end])
        ->sum('total_money');
        //已收
        $income = BillingModel::where('house_property_id', 'in', $result)
        ->whereTime('start_time', [$star, $end])
        ->whereNotNull('accounting_date')
        ->sum('total_money');
        //已付
        $spending = SumModel::where('house_property_id', 'in', $result)
        ->whereTime('accounting_date', [$star, $end])
        ->where('type', 'in', ['B', 'C', 'D', 'E', 'F'])
        ->sum('total_money');
        $this->assign('finance_info', [
            'server_time' => date('Y-m-d H:i:s', time()),
            'receivable' => $receivable,
            'income' => $income,
            'spending' => intval($spending),
            'profits' => $income - intval($spending),
        ]);
        return $this->fetch();
    }

    private function getMySQLVer()
    {
        $res = Db::query('SELECT VERSION() AS ver');
        return isset($res[0]) ? $res[0]['ver'] : '未知';
    }

    public function password()
    {
        if ($this->request->isPost()) {
            $password = $this->request->post('password/s', '');
            $this->auth->changePassword($password);
            $this->success('密码修改成功。');
        }
        return $this->fetch();
    }

    public function info(App $app)
    {
        $this->assign('server_info', [
            'server_version' => $this->request->server('SERVER_SOFTWARE'),
            'thinkphp_version' => $app->version(),
            'mysql_version' => $this->getMySQLVer(),
            'upload_max_filesize' => ini_get('file_uploads') ? ini_get('upload_max_filesize') : '已禁用',
            'max_execution_time' => ini_get('max_execution_time') . '秒'
        ]);
        return $this->fetch();
    }

    public function echar()
    {
        $loginUser = $this->auth->getLoginUser();
        $property = PropertyModel::where('admin_user_id', $loginUser['id'])->select()->toArray();
        $result = array_map(function ($item) {
            return $item['id'];
        }, $property);
        $categories = array();
        $incomeArr = array();
        $spendingArr = array();
        $profitsArr = array();
        for ($i=11; $i>=0; $i--) {
            $star = date("Y-m-01", strtotime("first day of -$i Months"));
            $end = date('Y-m-d', strtotime("$star +1 month -1 day"));
            $income = SumModel::where('house_property_id', 'in', $result)
            ->whereTime('accounting_date', [$star, $end])
            ->where('type', 'A')
            ->sum('total_money');
            $spending = SumModel::where('house_property_id', 'in', $result)
            ->whereTime('accounting_date', [$star, $end])
            ->where('type', 'in', ['B', 'C', 'D', 'E', 'F'])
            ->sum('total_money');
            \array_push($incomeArr, $income);
            \array_push($spendingArr, intval($spending));
            \array_push($profitsArr, $income - intval($spending));
            \array_push($categories, \substr($star, 0, 7));
        }

        return \json(
            ['categories' => $categories,
             'data' => ['income' => $incomeArr, 'spending' => $spendingArr, 'profits' => $profitsArr]
            ]
        );
    }
}
